// 导入Redux模块
import { createSlice } from "@reduxjs/toolkit";
//导入请求包
import axios from "axios";
// 导入AppDispatch声明类型
import type { AppDispatch } from "../index";

// 导入账单声明类型
import type { BillRequestType } from "../../types/billType";

// 创建一个名为 billStore 的 slice
export const billStore = createSlice({
  name: "BillStore",
  initialState: {
    // 账单数据
    billData: [] as BillRequestType[],
  },
  reducers: {
    // 设置账单数据
    setBillData: (state, action) => {
      state.billData = action.payload;
    },
    // 添加账单
    addBillData: (state, action: { payload: BillRequestType }) => {
      state.billData.push(action.payload);
    },
  },
});

//异步请求方法
// 获取账单数据
const getBillData = () => {
  return async (dispatch: AppDispatch) => {
    const res = await axios.get("http://localhost:1314/DataJson");
    dispatch(setBillData(res.data));
  };
};

// 添加账单数据
const addBillDataAPI = (data: BillRequestType) => {
  return async (dispatch: AppDispatch) => {
    const res = await axios.post("http://localhost:1314/DataJson", data);
    dispatch(addBillData(res.data));
  };
};

//导出异步请求方法
export { getBillData, addBillDataAPI };
// 为每个 case reducer 函数生成 Action creators
export const { setBillData, addBillData } = billStore.actions;
//导出reducer
export default billStore.reducer;
